package com.zlsy.thread.volatiledemo;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author zhouliang
 * @date 2020/2/27 10:29
 * @desc volatile 在这种情况下是无法使生产者停下来了的：
 *       生产者先生产10个放满队列，然后消费者一个一个消费，
 *       消费一个生产者放入一个，消费者消费到某个点之后不再消费了 ，
 *       生产者阻塞，进不了while (num <= 10000 && !canceled) 判断
 *       所以生产者线程无法停止
 */
public class WrongWayVolatileCantStop {
    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue storage = new ArrayBlockingQueue<>(10);
        Producer producer = new Producer(storage);
        Thread thread = new Thread(producer);
        thread.start();
        Thread.sleep(1000);

        Consumer consumer = new Consumer(storage);
        while (consumer.needMoreNums()) {
            System.out.println(consumer.storage.take() + "已经被消费了");
            Thread.sleep(100);
        }
        System.out.println("消费者不需要更多的数据了，请生产者停止生产！");
        //标记生产者的停止标记为true
        producer.canceled = true;
        System.out.println("生产者canceled为：" + producer.canceled);
    }
}

class Producer implements Runnable {
    public volatile boolean canceled = false;
    ArrayBlockingQueue storage;

    public Producer(ArrayBlockingQueue storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        try {
            int num = 0;
            while (num <= 10000 && !canceled) {
                if (num % 100 == 0) {
                    //当有符合条件的num的时候生产者开始生产放入生产队列，但是只能放十个就阻塞了。
                    storage.put(num);
                    System.out.println(num + "是一百的倍数，放到仓库中了");
                }
                num++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("生产者停止运行！");
        }
    }
}

class Consumer {
    ArrayBlockingQueue storage;

    public Consumer(ArrayBlockingQueue storage) {
        this.storage = storage;
    }

    public boolean needMoreNums() {
        if (Math.random() > 0.95) {
            return false;
        }
        return true;
    }

}